<template>
  <el-card shadow="never" class="border-0">

    <!-- 搜索 -->
    <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
      <el-row :gutter="20">
        <el-col :span="5">
            <el-form-item label="模板名称">
              <el-select v-model="searchForm.templateId" filterable placeholder="模板名称">
                <el-option
                  v-for="item in templateDic"
                  :key="item.templateId"
                  :label="item.templateName"
                  :value="item.templateId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        <el-col :span="5">
          <div class="flex items-center justify-end">
            <el-button type="primary" @click="initTableData(1)">搜索</el-button>
            <el-button @click="resetSearchForm">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格数据 -->
    <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">
      <el-table-column label="模版名称" align="center">
        <template #default="{ row }">
          {{ row.templateName }}
        </template>
      </el-table-column>

      <el-table-column label="申请人" align="center">
        <template #default="{ row }">
          {{ row.applicantName }}
        </template>
      </el-table-column>

      <el-table-column label="审批结果" align="center">
        <template #default="{ row }">
          {{ formatRecordResult(row.approvalResult) }}
        </template>
      </el-table-column>

      <el-table-column label="审批备注" align="center" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.comments }}
        </template>
      </el-table-column>

      <el-table-column label="审批时间" align="center">
        <template #default="{ row }">
          {{ dateFormatter(row.approvalTime) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" text @click="handleShow(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="flex items-center justify-center mt-5">
      <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage" :page-size="limit"
        @current-change="initTableData" />
    </div>
  </el-card>

  <!-- 查看详情弹窗 -->
  <el-dialog v-model="approvalDetailDialogVisible" title="详情信息" width="40%" align-center>
    <el-form :model="approvalDetail" label-width="120px" :inline="false">
      <el-form-item label="申请人：">
        <span>{{ approvalDetail.approvalRequestDto.applicantName }}</span>
      </el-form-item>
      <el-form-item label="模板名称：">
        <span>{{ approvalDetail.approvalTemplateDto.templateName }}</span>
      </el-form-item>
      <el-form-item label="申请描述：">
        <span>{{ approvalDetail.approvalRequestDto.description }}</span>
      </el-form-item>
      <el-form-item label="审批状态：">
        <span>{{ formatRequestStatus(approvalDetail.approvalRequestDto.status) }}</span>
      </el-form-item>

      <el-steps :align-center="true">
          <el-tooltip 
            class="item" 
            effect="dark" 
            placement="top-start"
            v-for="(item, key) in steps" :key="key"
            :content="item.tooltipInfo">
            <el-step  
                :title="item.title" 
                :status="item.status">
                <template #description>
                  <!-- 或签 -->
                  <div v-if="item.approvalType == 1">
                    <span>{{ item.description }}</span>
                  </div>
                  <!-- 会签 -->
                  <div v-if="item.approvalType == 2" 
                    v-for="(desc, key) in item.description"
                    :key="desc.key" style="font-size: 13px;">
                    <span>{{ desc.name }}</span><span>({{ desc.result }})</span><br><span>{{ desc.time }}</span>
                  </div>
              </template>
            </el-step>
          </el-tooltip>
      </el-steps>

      <el-form-item v-if="approvalDetail.approvalRequestDto.remark" label="拒绝原因：">
        <span>{{ approvalDetail.approvalRequestDto.remark }}</span>
      </el-form-item>

      <el-form-item v-if="approvalDetail.approvalRequestDto.imageUrls != null" label="图片：">
        <el-image style="width: 100px; height: 100px; margin-left: 5px;" 
          v-for="item in approvalDetail.imagesDto"
          :key="item.url"
          :src="item.url"
          :preview-src-list="item.srcList"
          fit="cover"
        />
      </el-form-item>

    </el-form>
    <template #footer>
        <div>
            <el-button type="primary" @click="approvalDetailDialogVisible = false">
                关闭
            </el-button>
        </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue"
import { dateFormatter } from '~/utils/common.js'
import { getApprovalTemplateList,formatRequestStatus,formatRecordResult,getRecordDone,getRequestInfoById } from "~/api/approvalApi"

// 审批详情弹窗
const approvalDetailDialogVisible = ref(false)
// 审批详情
const approvalDetail = reactive({
  approvalTemplateDto:null,
  approvalRequestDto:null,
  imagesDto: null
})
// steps
const steps = ref([])

// 分页
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)

// 查询条件
const searchForm = reactive({
  templateId: null,
  page: currentPage.value,
  size: limit.value,
})

// 重置搜索框
const resetSearchForm = () => {
  searchForm.templateId = null
  initTableData(1)
}

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 模板字典数据
const templateDic = ref([])

// 生命周期函数
onMounted(() => {
  //初始化模板字典数据
  initTemplateDic()
  //初始化列表数据
  initTableData()
})

// 获取模板字典数据
function initTemplateDic() {
  getApprovalTemplateList()
    .then(res => {
      if(res){
        templateDic.value = res.filter(template => template.state == 1)    
      }
    })
}

// 获取数据
function initTableData(p = null) {
  //指定页码是否为空
  if (typeof p == "number") {
    currentPage.value = p
  }

  loading.value = true
  searchForm.page = currentPage.value

  getRecordDone(searchForm)
    .then(res => {
      if(res && res.records){
          tableData.value = res.records      
          total.value = res.total
        }else{
          tableData.value = []  
          total.value = 0
        }
    })
    .finally(() => {
      loading.value = false
    })
}

// 查看详情
const handleShow = (row) => {
  getRequestInfoById(row.requestId)
    .then(res => {
      approvalDetail.approvalTemplateDto = res.approvalTemplateDto
      approvalDetail.approvalRequestDto = res.approvalRequestDto
      let imageUrls = res.approvalRequestDto.imageUrls
      if(null != imageUrls && imageUrls.length>0){
        let result = []
        let imgs = imageUrls.split(",")
        let item = null
        for(let i=0;i<imgs.length;i++){
          item = {}
          item.url = imgs[i]
          item.srcList = [imgs[i]]
          result.push(item)
        }
        approvalDetail.imagesDto = result
      }

      //构建流程节点图
      let nodeList = res.approvalTemplateDto.nodeDtoList
      steps.value = []
      let defaultStep = {approvalType: 1,title:"提交申请",status:"success",tooltipInfo:"流程起点",description: dateFormatter(res.approvalRequestDto.createTime)}
      steps.value.push(defaultStep)
      let step = null
      //会签描述信息
      let descList = []
      //审核人list
      let nameList = []
      //审核结果list
      let resultList = []
      //审核时间list
      let resultDateList = []
      //审核备注信息
      let commentsList = []

      for(let i=0;i<nodeList.length;i++){

        //重置数据---------
        step = {}
        descList = []
        nameList = []
        resultList = []
        resultDateList = []
        commentsList= []
        //重置数据---------

        //当前节点审批方式
        let approvalType = nodeList[i].approvalType
        //获取审批人list
        let approvalRecordList = nodeList[i].approvalRecordDtos
        for(let j=0;j<approvalRecordList.length;j++){
          nameList.push(approvalRecordList[j].approverName)
          resultList.push(approvalRecordList[j].approvalResult)
          resultDateList.push(dateFormatter(approvalRecordList[j].approvalTime))
          commentsList.push(approvalRecordList[j].comments)
          //会签特殊处理描述字段
          if(approvalType == 2){
            let desc = {}
            desc.key = j
            desc.name = nameList[j]
            desc.result = formatRecordResult(resultList[j])
            desc.time = resultDateList[j]
            descList.push(desc)
          }
        }

        //提示信息
        step.tooltipInfo = "处理人: " + nameList.join("; ")

        //审批类型，1：或签，2：会签
        if(nodeList[i].approvalType == 1){
          //审批类型
          step.approvalType = 1

          //审批结果，0未处理，1：同意，2：拒绝，3：处理中，4：他人已处理
          if(resultList.indexOf(0) !== -1){
              //标题
              step.title = "未处理"
              //节点描述
              step.description = null
              //节点状态
              step.status = "wait"
              steps.value.push(step)
          }else if(resultList.indexOf(3) !== -1){
              //标题
              step.title = "处理中"
              //节点描述
              step.description = null
              //节点状态
              step.status = "process"
              steps.value.push(step)
          }else if(resultList.indexOf(1) !== -1){
              let successIndex = resultList.indexOf(1)
              //标题（此处是审核人）
              step.title = nameList[successIndex]
              //节点描述（此处是审核时间）
              step.description = resultDateList[successIndex]
              //节点状态；审批结果，0未处理，1：同意，2：拒绝，3：处理中，4：他人已处理
              step.status = "success"
              steps.value.push(step)
          }else if(resultList.indexOf(2) !== -1){
              let errorIndex = resultList.indexOf(2)
              //标题（此处是审核人）
              step.title = nameList[errorIndex]
              //节点描述（此处是审核时间）
              step.description = resultDateList[errorIndex]
              //节点状态；审批结果，0未处理，1：同意，2：拒绝，3：处理中，4：他人已处理
              step.status = "error"
              //如果是拒绝显示原因
              approvalDetail.approvalRequestDto.remark = commentsList[errorIndex]

              steps.value.push(step)
          }
        }

        else if(nodeList[i].approvalType == 2){
          //审批类型
          step.approvalType = 2

          //审批结果，0未处理，1：同意，2：拒绝，3：处理中，4：他人已处理
          if(resultList.indexOf(0) !== -1){
            //标题
            step.title = "未处理"
            //节点描述
            step.description = null
            //节点状态
            step.status = "wait"
            steps.value.push(step)
          }else{
            //标题
            step.title = null
            //节点状态
            if(resultList.indexOf(2) !== -1){
              step.status = "error"
              //如果是拒绝显示原因
              approvalDetail.approvalRequestDto.remark = commentsList[resultList.indexOf(2)]

            }else if(resultList.indexOf(3) !== -1){
              step.status = "process"
            }else{
              step.status = "success"
            }
            step.description = descList
            steps.value.push(step)
          }
        }
      }

      //申请人名称
      approvalDetail.approvalRequestDto.applicantName = row.applicantName

      approvalDetailDialogVisible.value = true
    })
}
</script>

<style lang="scss">
.el-step__head.is-process{
  border-color:darkorange;
  color: darkorange
}
.el-step__title.is-process{
  color: darkorange
}
</style>